<?php
/**
 +--------------------------------
 * BaseAction.php 所有操作的基类
 +--------------------------------
 *
 * @param $dao 操作模型
 */
class BaseAction extends Action{
    protected $dao,$userid,$username,$roles,$_arr_discount,$dao_supplier='supplier',$dao_erp='erp';
    protected $listrows,$orderField,$orderDirection,$keywords,$order,$createtime,$mtime,$endtime,$starttime;//默认系统变量
    function _initialize() {
        self::_islogin();
        self::_settpl();
        import("ORG.Util.Page");
        load("@.extend");
		
		import("Com.User");
		import("Com.Agent");
		import("Com.Biz");
		import("Com.Kit");
		import("Com.Money");
		import("Com.KitMoney");
		import("Com.KitOrder");
		//套件下单折扣
		$this->_arr_discount = array(1=>C('DEFAULT_PROVINCE_DISCOUNT'),2=>C('DEFAULT_CITY_DISCOUNT'),3=>C('DEFAULT_AREA_DISCOUNT'),4=>C('DEFAULT_AGENTS_DISCOUNT'));
    }
	/**
	 * 套件订单列表
	 * @param array     $_role_level=array()
	 * @return message
	 * */
	function exist_role($_role_level=array()){
		$is_role = 0;
		foreach ($this->roles as $key => $value) {
			if(in_array($value, $_role_level)){
				++$is_role;
			}
		}
		if($is_role==0){
			$this->_ajm(300,'您没有操作当前页权限',0);
		}
	}
    /**
     * 设置模版常用的默认系统变量
     */
    protected function _settpl(){
        $this->assign('action_name',ACTION_NAME);
        $this->assign('module_name',MODULE_NAME);
        $this->assign('now_url',MODULE_NAME.'/'.ACTION_NAME);
        $this->assign('pageNum',$_REQUEST['pageNum']?$_REQUEST['pageNum']:1);
        $this->assign("starttime",$_POST['starttime']);
        $this->assign("endtime",$_POST['endtime']);
        $this->listrows=$_REQUEST['numPerPage']?$_REQUEST['numPerPage']:20;
        $this->assign('numPerPage',$this->listrows);
        $this->orderField=$_REQUEST['orderField']?$_REQUEST['orderField']:'id';
        $this->assign('orderField',$this->orderField);
        $this->orderDirection=$_REQUEST['orderDirection']?$_REQUEST['orderDirection']:'DESC';
        $this->assign('orderDirection',$this->orderDirection);
        $this->order=$this->orderField.' '.$this->orderDirection;
        $this->keywords=trim($_REQUEST['keywords'])?trim($_REQUEST['keywords']):trim($_REQUEST['keywords_keywords']);
        $this->assign('keywords',$this->keywords);
		$this->createtime=$_REQUEST['ctime']?$_REQUEST['ctime']:'createtime';//创建时间的字段名
		$this->mtime=$_REQUEST['mtime']?$_REQUEST['mtime']:'mtime';
		$this->endtime=$_REQUEST['endtime']?$_REQUEST['endtime']:'endtime';
		$this->starttime=$_REQUEST['starttime']?$_REQUEST['starttime']:'starttime';
		$area=F('Area');
		if(empty($area)){
			$area=M('Area')->select();
			$area=field2key($area,'id');
			F('Area',$area);
		}
		$this->assign('Area',$area);
		self::plogs();
    }

    /**
     * 缓存部门、岗位、专业
     * @param $isRenew 是否缓存  0 为不更新  1为更新
     * @param $modelName 设置需要更新缓存的文件名
     * @return array $list
     */
    protected function _cache($isRenew = 0,$modelName='all'){
        //与部门dept有关缓存操作
        if($modelName == 'sys' || $modelName == 'all'){
            if($isRenew == 0){
                break;
            }else{
                //缓存部门相关信息，以id作为主键
                $dao = M('SystemConfig');
                $syslist = $dao->select();
                $list=field2key($syslist,'id');
                F("SYS",$list);
            }
        }

        //已显示品牌缓存
        if($modelName == 'brands' || $modelName == 'all'){
            if($isRenew == 0){
                break;
            }else{
                //缓存部门相关信息，以id作为主键
                $dao = M('ProductBrand');
                $where=array('status'=>1);
                $brandslist = $dao->where($where)->select();
                $list=field2key($brandslist,'id');
                F("brands",$list);
            }
        }

        //已显示品牌缓存
        if($modelName == 'cats' || $modelName == 'all'){
            if($isRenew == 0){
                break;
            }else{
                //缓存分类相关信息，以id作为主键
                $dao = M('ProductCategoryTag');
                $where=array('status'=>1,'modelcat'=>'product');
                $where['type']=array('eq','1');
                $categoryslist = $dao->where($where)->select();
                $list=field2key($categoryslist,'id');
                F("cats",$list);
            }
        }
        //已显示角色缓存
        if($modelName == 'role' || $modelName == 'all'){
        	if($isRenew == 0){
        		break;
        	}else{
        		//缓存分类相关信息，以id作为主键
        		$dao = M('Role');
        		$rolelist = $dao->select();
        		$list=field2key($rolelist,'id');
        		F("role",$list);
        	}
        }
        
        return $list;
    }

    /**
     * 登陆检查
     */
    function _islogin(){
        if(empty($_SESSION['userid'])){
        	if(ACTION_NAME=='index'&&MODULE_NAME=='Index'){
        		$this->redirect("Auth/login");
        		$this->assign('jumpUrl',U("Auth/login"));
        		$this->error("请先登陆.");
        	}else{
            	$this->_ajm(301,'登陆超时');
        	}
        }else{
        	import("Com.User");
        	$user=new User();
        	$this->userid=$_SESSION['userid'];
        	$this->username=$_SESSION['userinfo']['username'];
        	$this->roles=arr_to_explode($_SESSION['role_ext']['role_user'],'role_id');
        }
    }


    /**
     * 查询某个字段是否存在
     * @return json 如果存在返回false，不存在返回true
     */
    public function field_exist(){
        $tn = $_REQUEST['tn'];
        $fn = $_REQUEST['fn'];
        $val = $_REQUEST[$fn];

        $dao = M($tn);
        $rel = $dao->where($fn."='".$val."'")->find();
        if($rel === false || empty($rel)){
            echo json_encode(true);
        }else{
            echo json_encode(FALSE);
        }
    }
    /**
     * 通用的列表页
     */
    public function index($maps=array(),$dao=FALSE){
        $dao=$dao?$dao:$this->dao;
        $condition=array();
        $maps = self::create_where($maps);
        //处理maps数据
        if($_REQUEST['map']){
            $map=array();
            foreach ($_REQUEST['map'] as $key => $value) {
                if($value!='all'&&!empty($value)){
                    $condition[$key]=$value;
                }
                $map[$key]=$value;
            }
            $this->assign("map",$map);
        }

        if($_POST['starttime']){
            $starttime='';
            $starttime=gettime($_POST['starttime']);
        }
        if($_POST['endtime']){
            $endtime='';
            $endtime=gettime($_POST['endtime']);
        }
		$createtime=$this->createtime;
        if($starttime&&$endtime){
            $condition[$createtime]=array(array('gt',$starttime),array('lt',$endtime),'AND');
        }elseif($starttime){
            $condition[$createtime]=array('gt',$starttime);
        }elseif($endtime){
            $condition[$createtime]=array('lt',$endtime);
        }

        $condition=array_merge($condition,$maps);
        $count=$dao->where($condition)->count();
        //echo($dao->getlastsql());
        $this->assign("totalCount",$count);
        if($count>0){
            $page=new Page($count,$this->listrows);
            $list=$dao->where($condition)->order($this->order)->limit($page->firstRow.','.$page->listRows)->select();
            //echo($dao->getlastsql());
            $this->assign('list',$list);
        }
        $this->display();
    }
	/**
	 * 组合查询条件
	 */
	function create_where($maps=array()){
		$condition=array();
        if($this->keywords){
        	$sfield = $_REQUEST['sfield'];
        	if($sfield!='all' && $sfield!=''){
        		$condition[$sfield] =array('LIKE','%'.$this->keywords.'%');
        		$num = strpos($sfield,'.');
        		$fields = empty($num) ? $sfield : substr($sfield, $num+1,strlen($sfield)); //wherefields 存值改成  $fields 后，页面会出现错误，暂时先保留
        		if(strstr($sfield,'.')){
        			$sfield=substr(strstr($sfield,'.'), 1,strlen(strstr($sfield,'.'))-1);
        		} 
        		$this->assign('wherefields',$sfield);
        	}else{
	            $wherefields=explode(',',$_REQUEST['sfield_name']);
	            if(in_array($_REQUEST['wherefields'], $wherefields)){
	                $wherefields=$_REQUEST['wherefields'];
	                $condition[$wherefields]=array("like",'%'.$this->keywords.'%');
	                $this->assign('wherefields',$wherefields);
	            }else{
	                $map=array();
	                foreach ($wherefields as $value) {
	                    $map[$value]=array("like",'%'.$this->keywords.'%');
	                }
	                $map['_logic'] = 'or';
	                $condition['_complex'] = $map;
	                $this->assign('wherefields','all');
	            }
        	}
        }
        //处理maps数据
        if($_REQUEST['map']){
            $map=array();
            foreach ($_REQUEST['map'] as $key => $value) {
                if($value!='all'&&!empty($value)){
                    $condition[$key]=$value;
                }
                $map[$key]=$value;
            }
            $this->assign("map",$map);
        }

//         if($_POST['starttime']){
//             $starttime='';
//             $starttime=gettime($_POST['starttime']);
//         }
//         if($_POST['endtime']){
//             $endtime='';
//             $endtime=gettime($_POST['endtime']);
//         }
// 		$createtime=$this->createtime;
//         if($starttime&&$endtime){
//             $condition[$createtime]=array(array('gt',$starttime),array('lt',$endtime),'AND');
//         }elseif($starttime){
//             $condition[$createtime]=array('gt',$starttime);
//         }elseif($endtime){
//             $condition[$createtime]=array('lt',$endtime);
//         }
        $condition=array_merge($condition,$maps);
		return $condition;
	}
	
	
	/**
	 * 通用的时间处理
	 * @author tb
	 * @param $time = array('stime'=>12223212,'etime'=>24243234)
	 * @param $field 匹配字段
	 */
	function create_date($time = array(),$field,$where = array()){
		if($time['stime'] && $time['etime']){
			$where[$field] = array('between',array($time['stime'],$time['etime']));
		}elseif($time['stime']){
			$where[$field] = array('EGT',$time['stime']);
		}elseif($time['etime']){
			$where[$field] = array('ELT',$time['etime']);
		}
		return $where;
	}
	
    /**
     * DWZ 通用的列表页
     * $maps["_field"]：用于定义要查询的字段
     */
    public function dwz_list($maps=array(),$dao=FALSE,$template_name=''){
        if(!is_array($maps) && is_object($maps)) {
            $dao = $maps;
            $maps = array();
        }
        $dao=$dao?$dao:$this->dao;
        unset($maps["_field"]);

        $condition=array();
        if($this->keywords){
            $sfield_name = $_REQUEST['sfield_name'];
            $condition[$sfield_name] = array("like",'%'.$this->keywords.'%');
            $this->assign("sfield_name", $sfield_name);
        }
        $order=$this->orderField.' '.$this->orderDirection;
        $condition=array_merge($condition,$maps);
        $count=$dao->where($condition)->order($order)->count();
        $this->assign("totalCount",$count);

        if($count>0){
            $page=new Page($count,$this->listrows);
	        $is_field = array_key_exists("_field", $maps)?$maps["_field"]:false;
			if(method_exists($dao, "relation")) {
				$dao = $dao->relation(true);
			}
			if($is_field) {
				$dao = $dao->field($is_field);
			}
            $list=$dao->where($condition)->order($order)->limit($page->firstRow.','.$page->listRows)->select();
            $this->assign('list',$list);//echo $dao->getLastSql();
        }//var_dump($list);
        $this->display($template_name);
    }
    /**
     * 添加
     */
    function add(){
        $this->display();
    }
    /**
     * 通用编辑
     */
    function edit($dao=false){
        $id=intval($_REQUEST['id']);
        if(empty($id)){
            $this->_ajm(300,'请选择一条需要修改的数据',0);
        }
        $dao=$dao?$dao:$this->dao;
        $info=$dao->where("id=".$id)->find();
        if(empty($info)){
            $this->_ajm(300,'操作错误，请重试',0);
        }
        $this->assign("info",$info);
        $this->display('add');
    }
    /**
     * 添加数据
     */
    function insert($dao=false,$url=false){
        $dao=$dao?$dao:$this->dao;
        $data=$dao->create();
        if($data===FALSE){
            $this->_ajm(300,'数据创建失败，请重试',0);
        }
        $id=$dao->add($data);
        if($id===FALSE){
            $this->_ajm(300,'数据写入失败，请重试'.$dao->getlastsql(),0);
        }else{
            $this->_ajm(200,'数据添加成功',0,$url?$url:U(MODULE_NAME.'/index'));
        }
    }
    /**
     * 更新数据
     */
    function update($dao=false,$url=false){
        $dao   = $dao ? $dao : $this->dao;
        $_POST = array_merge($_REQUEST,$_POST);
        if(empty($_POST['id'])){
            $this->_ajm(300,'请选择一条需要修改的数据',0);
        }
        $data=$dao->create();
        if($data===FALSE){
            $this->_ajm(300,'数据创建失败，请重试',0);
        }
        $id=$dao->save();
        if($id===FALSE){
            $this->_ajm(300,'数据写入失败，请重试',0);
        }else{
            $this->_ajm(200,'数据修改成功',0,$url?$url:U(MODULE_NAME.'/index'));
        }
    }
    /**
     * 批量删除
     */
    function delall($dao,$url=false){
        $dao=$dao?$dao:$this->dao;
        $pk=$dao->getPk();
        $id=intval($_REQUEST['id']);
        $ids=$_REQUEST['ids'];
        $where=array();
        if(empty($id)){
            $ids=implode(',',$ids);
            $where[$pk]=array('IN',$ids);
        }else{
            $where[$pk]=array('eq',$id);
        }
        $res=$dao->where($where)->delete();
        if($res===FALSE){
            $this->_ajm(300,'操作错误，请重试');
        }else{
            $this->_ajm(200,'操作成功',1,$url?$url:U(MODULE_NAME.'/index'));
        }
    }
    /**
     * 查看单条信息
     */
    function detail($dao){
        $dao=$dao?$dao:$this->dao;
        $pk=$dao->getPk();
        $where=array();
        $id=intval($_REQUEST['id']);
        if(empty($id)){
            $this->_ajm(300,'请选择一条数据查看',0);
        }
        $where[$pk]=array('eq',$id);
        $res=$dao->where($where)->find();
        if(empty($res)){
            $this->_ajm(300,'查询数据出错或者查询的数据不存在',0);
        }
        $this->assign("info",$res);
        $this->display();
    }
    /**
     * 联动提示效果
     */
    function suggest($maps=false,$res=false){
        $tn = $_REQUEST['tn'];
        $fn = $_REQUEST['fn'];
        $dao=$tn?D($tn):D(MODULE_NAME);
        $map=$condition=array();
        $order='id asc';
        $field=$_REQUEST['field']?$_REQUEST['field']:$fn;
        $fields=array();
        if($this->keywords){
            if(strpos($field,',')!==FALSE){
            	if(strpos($fn,',')!==FALSE){
            		$fns=explode(',', $fn);
            	}
                $fnarr=explode(',', $field);
                foreach($fnarr as $k=>$v){
                    $map[$v]=array("like",'%'.$this->keywords.'%');
                    if($fns[$k]){
                    $fields[]=$v.' as '.$fns[$k];
                    }else{
                    	$fields[]=$v;
                    }
                }
                $map['_logic'] = 'or';
                $condition['_complex'] = $map;
                $fields=implode(',', $fields);
            }else{
            	$fields=$field;
                $map[$field]=array("like",'%'.$this->keywords.'%');
                $condition = array_merge($condition,$map);
            }
        }else{
        	$fields = $field;
        	$pk=$dao->getpk();
        	$order=$pk." ASC";
        }
        if($_REQUEST['where']){
        	$this->assign('where',$_REQUEST['where']);
        	$where=mydecode($_REQUEST['where'],1);
        	$condition = array_merge($condition,$where);
        }
        if($maps){
            $condition = array_merge($condition,$maps);
        }
        $list=$dao->field($fields)->where($condition)->order($order)->limit("0,30")->select();
        //dump($dao->getLastSql());
        if($res!==false){
        	return $list;
        }
        echo json_encode($list);
    }
    /**
     * 联动提示效果
     */
    function lookup($maps=false){
    	$tn = $_REQUEST['tn'];
    	$this->assign('tn',$tn);
    	$fn = $_REQUEST['fn'];
    	$this->assign('fn',$fn);
    	$dao=$tn?M($tn):M(MODULE_NAME);
    	$map=$condition=array();
    	if($this->keywords){
    		if(strpos($fn,',')!==FALSE){
    			$fnarr=explode(',', $fn);
    			foreach($fnarr as $v){
    				$map[$v]=array("like",'%'.$this->keywords.'%');
    			}
    			$map['_logic'] = 'or';
    			$condition['_complex'] = $map;
    		}else{
    			$map[$fn]=array("like",'%'.$this->keywords.'%');
    			$condition = array_merge($condition,$map);
    		}
    	}
    	if($_REQUEST['where']){
    		$this->assign('where',$_REQUEST['where']);
    		$where=mydecode($_REQUEST['where'],1);
    		$condition = array_merge($condition,$where);
    	}
    	if($maps){
    		$condition = array_merge($condition,$maps);
    	}
    	$pk=$dao->getpk();
    	$f = $_REQUEST['field'];
    	$this->assign('field',$f);
    	$field=$_REQUEST['field']?$f:$fn;
    	$count=$dao->where($condition)->count();
    	$this->assign("totalCount",$count);
    	if($count>0){
    		$page=new Page($count,$this->listrows);
    		$list=$dao->field($field)->where($condition)->order($this->order)->limit($page->firstRow.','.$page->listRows)->select();
    		//echo ($dao->getLastSql());
    		$this->assign('list',$list);
    	}
    	
    	$this->display();
    }
    /*
     * 单个文件上传
     * @author tb
     * @date 2014.1.11
     * */
    function file_upload() {
    	$config = array ();
    	$imagepath = self::_upload ( $config );
    	echo $imagepath;
    }
    /*
     * 多个文件上传
     * @author tb
     * @date 2014.1.11
    * */
    function file_uploads() {
    	$verifyToken = md5('unique_salt' . $_POST['timestamp']);
    	if(empty($_POST['timestamp'])&&$_POST['token'] != $verifyToken){
    		echo '非法文件类型';
    		exit;
    	}
    	$config = array ();
    	$imagepath = self::_upload ( $config );
    	echo $imagepath;
    }
    /**
     * 在线编辑图片上传
     */
    function upload() {
    	$config = array ();
    	$imagepath = self::_upload ( $config );
    	$msg = "{'url':'" . $imagepath . "'}";
    	$err = '';
    	echo "{'err':'" . self::jsonString ( $err ) . "','msg':" . $msg . "}";
    }
    function jsonString($str) {
    	return preg_replace ( "/([\\\\\/'])/", '\\\$1', $str );
    }
    /**
     * 处理文件上传
     * @param $config array 上传参数一些设置
     * @return string 图片文件的路径
     */
    function _upload($config=array()) {
    	// 引入上传类，并设置参数值
    	import ( "ORG.Net.UploadFile" );
    	$config['maxSize']       = $config['maxSize'] ? $config['maxSize'] : 300292200;
    	$config['uploadReplace'] = isset($config['uploadReplace']) ? $config['uploadReplace'] : true;
    	$config['savePath']      = $config['savePath'] ? $config['savePath'] : './91Uploads/' . date ( 'Y-m' ) . '/';
    	if ( $config['allowExts'] && is_string($config['allowExts']) ) $config['allowExts'] = explode ( ',', $config['allowExts'] );
    	// 开始上传
    	$upload = new UploadFile ( $config );
    	if (! $upload->upload ()) {
    		$this->error ( $upload->getErrorMsg () );
    	} else {
    		$uploadList = $upload->getUploadFileInfo ();
    		$imgpath= $upload->savePath . $uploadList [0] ['savename'];
    	}
    	return $imgpath;
    }
    /**
     * ajax返回信息
     * @param int $status=200 状态码  200成功  300失败  301超时
     * @param string $message="操作成功"
     * @param $flag = 0表示关闭   $flag = 1表示刷新  $flag = 2确定之后再刷新
     * @param $forwardUrl $flag为1、2时需要操作的页面
     * @return JSON
     */
    function _ajm($status=200,$message="操作成功",$flag=0,$forwardUrl=false,$navTabId='',$data=array()){
        $addState = array('statusCode'=>$status,'message'=>$message,'data'=>$data);
        switch($flag){
        case 0:
            $addState['callbackType'] = 'closeCurrent';
            $addState['navTabId'] =$navTabId;
            break;
        case 1:
            $addState['callbackType'] = 'forward';break;
        case 2:
            $addState['callbackType'] = 'forwardConfirm';break;
        default:
            if($flag !=''){
                $addState['callbackType'] = $flag;
            }
        }
        if($forwardUrl){
            $addState['forwardUrl'] = $forwardUrl;
        }
        exit(json_encode($addState));
    }
    /**
     * 返回分类树
     *@date 2013-6-3
     *@time 下午4:57:17
     */
    function cats_tree($urls = 'Cat/all') {
    //返回分类树
    	$cats=F("cats");
    	$this->assign("cats",$cats);
    	$cats=list_to_tree($cats,'id','parent_id');
		$cats=$cats[0]['_child'];
    	$tree=tree($cats,$urls);
    	$this->assign("tree",$tree);
    }//end cats_tree
   /**
	*获取产品的优惠信息
	*@date 2013-8-9
	*@time 下午12:13:47
	*@param array $pid 产品ID
	*@param string $subject 优惠的科目,多个科目使用 array('IN','BV,MV')
	*@param array $field 多维数组时产品ID的键名
	*@return array
	*/
	function product_coupon($pid=array(),$subject='BV',$field='') {
	//获取产品的优惠信息
		if(!is_array($subject)){
			$subject=strtoupper($subject);
		}
		$where=array();
		if(is_array($pid)&&$field==''){
			$where['product_id']=array('in',implode(',', $pid));
		}elseif(is_array($pid)&&$field!=''){
			$temp=array();
			foreach ($pid as $v){
				if(intval($v[$field])){
					$temp[]=intval($v[$field]);
				}
			}
			$where['product_id']=array('in',implode(',', $pid));
		}else{
			$where['product_id']=$pid;
		}
		$res=array();
		if($where['product_id']){
			$dao=M('ProductCoupon');
			$where['status']=1;
			$where['platform']=$this->_platform;
			if('ALL'!=$subject){
				$where['subject']=$subject;
			}
			$temp=$dao->where($where)->select();
			foreach ($temp as $v){
				$res[$v['product_id']][$v['subject']][]=$v;
			}
		}
		return $res;
	}//end product_coupon
    /**
     *判断某个时间是否过期
     *@date 2013-9-14
     *@param string $st 开始日期
     *@param string $et 结束日期
     *@return int $enable
     */
    function checktime($st,$et){
    	$time = time();
    	if($st>$time){
    		return 2;
    	}
    	if((!$st && $et && $et>=$time) || ($st && !$et && $st<=$time) || (!$st && !$et) ||($st && $et && $st<=$time && $et>=$time)){
    		return 1;
    	}else {
    		return 0;
    	}
    }
	/**
	* bakcv增加积分
	**/
	function addbackcv($user_id = 0,$content = '',$chpoint = 1,$status = 0){
		$arrd = getdate(); 
		$mon = $arrd['year'].$arrd['mon'];
		$firstday = date("Y-m-01");
		$now = date("Y-m-d h:i:s");
		//$now = gettimeofday();
		$sql1 = "SELECT SUM( chpoint ) sum FROM `bakcv` WHERE STATUS=".$status." and user_id=".$user_id." and ctime BETWEEN ".strtotime($firstday)." and ".strtotime($now);
		//$sql1 = "SELECT SUM( chpoint ) sum FROM `bakcv` WHERE STATUS=".$status." and user_id=".$user_id." and ctime BETWEEN ".strtotime($firstday)." and ".$now[sec];

		$nowpoint = M()->query($sql1);

		if(($nowpoint[0]["sum"] == "null" || $nowpoint[0]["sum"]=="")||$nowpoint[0]["sum"] == null){
			$nowpoint = 0;
		}else{
			$nowpoint = $nowpoint[0]["sum"];
		} 
		$nowpoint += $chpoint;
		$sql = "INSERT INTO `bakcv`( `user_id`, `type`, `chpoint`, `nowpoint`, `mon`, `ctime`, `content`, `status`) VALUES (".$user_id.",'0',".$chpoint.",".$nowpoint.",".$mon.",".strtotime($now).",'".$content."',".$status.")";
		//$sql = "INSERT INTO `bakcv`( `user_id`, `type`, `chpoint`, `nowpoint`, `mon`, `ctime`, `content`, `status`) VALUES (".$user_id.",'0',".$chpoint.",".$nowpoint.",".$mon.",".$now[sec].",'".$content."',".$status.")";
		$blag = M()->query($sql);
		
		return $blag;
	}
	/**
	 * 二维数组返回一维或字符串
	 * @param array $_arr
	 * @param string $_field
	 * @param string $_type 1为数组 2为字符串
	 * @return multitype:array|multitype:string
	 */
	function _arr2to1($_arr,$_field = '0',$_type = '1'){
		if ( ! $_arr ) return array();
		$arrayids = array();
		foreach ($_arr as $k => $v){
			$arrayids[$k] = $v[$_field];
		}
		if($_type != '1') $arrayids = implode(',',$arrayids);
	
		return $arrayids;
	}
	/**
	 *o2o的产品状态
	 *@date 2013-10-4
	 *@time 下午4:44:15
	 */
	function o2o_status($pid,$zt) {
		//o2o的产品状态
		$dao=M("ProductO2o");
		$data=array();
		$where['product_id'] = is_array($pid) ? array('IN',implode(',', $pid)) : $pid;
		$data['status']=$zt;
		if($zt == 1){
			$where['status'] = 0; //状态等于系统下架，重新上架商品
		}else{
			$where['status'] = 1; //状态为上架，系统下架商品
		}
		$dao->where($where)->save($data);
	}//end o2o_status
	/**
	 *获取省、市、县 名字
	 *@date 2013-10-4
	 *@time 下午4:44:15
	 */
	function get_areaname($id){
		$user = new User();
		$info = $user->get_data("area", array('id' => $id), "name", false);
		return $info['name'];
	}
	function area(){
		$id = intval ( $_REQUEST ['id'] );
		$level = intval ( $_REQUEST ['level'] );
		$user=new User();
		$arr = $user->area($id, $level);
		exit(json_encode($arr));
	}
	/**
	 * 系统操作日志
	 */
	protected function plogs(){
		$data=array();
		$data['userid']=$this->userid;
		$data['ctime']=time();
		$data['cip']=get_client_ip();
		$url  =  $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?");
		$parse = parse_url($url);
		parse_str($parse['query'],$params);
		foreach($params as $k=>$v){
			if(empty($v)){
				unset($params[$k]);
			}
		}
		if($_FILES){
			$_POST['_files']=$_FILES;
		}
		$params=http_build_query($params);
		$data['action']=$params;
		$data['other']=serialize($_POST);
		$dao=M('Plogs');
		$dao->add($data);
	}

	/**********************************
	*@结算专营商区域订单分成金额
	*@agent_id  not null 专营商id
	*@stype is null  商品类型
	*@ratio is null  分成比例
	*@starttime is null 开始时间
	*@shoptime is null 结束时间
	***********************************/	
	public function information($agent_id,$starttime,$shoptime){
		$stime= strtotime($starttime); 
		$endtime = strtotime($shoptime);
		$kitmoney = new KitMoney();
		$order = M('order');
		$aaoc = M('aaoc');
		$where = array();
		$where['platform'] = "SMW01";			
		if(!empty($agent_id)){
			$where['agent_id'] = $agent_id;
		}
		if(!empty($stime) && !empty($endtime)){
			$where['add_time'] = array(array('egt',$stime),array('elt',$endtime),'and');
		}
		$profit = M('user_agent_profit');
		$profit_info = $profit->where($where)->select();//获取分成比例	
		$agent_profit = array();
		foreach ($profit_info as $key => $value ){
			$agent_profit[$value['mname']]=$value['profit'];
		}
		unset($profit_info);		
		//查找这个专营商下面的所有订单ID
		$result = $order->where($where)->field('o.id')->join('as o inner join user_type as t ON o.userid = t.user_id')->select();	
		if(!$result){
			return false;
		}
		$order_all = array();
		foreach ($result as $r_key => $r_value ){
			$order_pay = $kitmoney->get_order_type_pay_total($r_value['id']);
			$temp_total = 0;
			$temp_profit_total = 0;
			foreach ($order_pay as $p_key => $p_value ){
				//dump($p_value);
				//$temp_total += $p_value['value'];
				//$temp_sum = (($p_value['value']/100) * $agent_profit[$p_value['mname']]);
				//$temp_profit_total += $temp_sum;
				$order_all[$r_value['id']][$p_value['mname']]['old'] = $p_value['value'];
				$order_all[$r_value['id']][$p_value['mname']]['profit'] = $agent_profit[$p_value['mname']];
				$order_all[$r_value['id']][$p_value['mname']]['cur'] = ((($p_value['value']/100) * $agent_profit[$p_value['mname']]) * 100);
			}
			//$order_all[$r_value['id']]['total'] = $temp_total;
			//$order_all[$r_value['id']]['profit_total'] = $temp_profit_total;
		}
		$total_sum = array();
		foreach ($order_all as $key => $value ){
			$k = array_keys($value);
			$total_sum[$k[0]]['old'] += $value[$k[0]]['old'];
			$total_sum[$k[0]]['profit'] = $value[$k[0]]['profit'];
			$total_sum[$k[0]]['cur'] += $value[$k[0]]['cur'];
		}
		foreach ($total_sum as $key => $value) {
			if(!empty($key)){
				$data = array();
				$data['agent_id'] = $agent_id; 
				$data['type'] = $key; 
				$data['ratio'] = $value['profit'];
				$data['starttime'] = $stime;
				$data['endtime'] = $endtime;
				$data['amount'] = $value['cur'];
				$data['aggregate_amount'] = $value['old'];
				$condition['agent_id'] = $agent_id;
				$condition['type'] = $key;
				$condition['starttime'] = $stime;
				$condition['endtime'] = $endtime;
				$aaocinfo = $aaoc->where($condition)->find ();
				//有结算状态之后 要添加结算拦截
				$data['id'] = $aaocinfo['id'];
				$ret = $aaoc->add($data,array(),true);
			}
		}
		return $ret;
	}
	
	/***********************
	*@订单实付金额
	*@$cn 订单编号
	*@$shoptype 商品类型
	***********************/	
	public function  payments($cn,$shoptype){
		$finance = M('order_real_pay');
		if(empty($cn)){
			return false; 
		}
		$total_price;
		$where = array();
		if(!empty($cn)){
			$where['order_id'] = $cn;
		}
		if(!empty($shoptype)){
			$where['mname'] = $shoptype;
		}
		$result = $finance->where($where)->select();
	
		if($result){
			foreach($result as $value){
				$price += $value['value'];
			}
			return $price;
		}else{
			return false;
		}
	}
}

